Scalar Types, Operators, & Control Flow
relational operators, control flow, & while-loops
Relational Operators
- true/false bool type
- true/false bool type
- == value equality / equivalence
- != value inequality / inequivalence
- < less-than
- > greater-than
- <= less-than or equal
- >= greater=than or equal
Control Flow
Conditional statement: Branch execution based on the value of an expression
Else-clause
While-loops
Relational Operators
break
- Python requires the use of while True and break
- break jumps out of the inner-most executing loop to the line immediately after it
Summary
- int, float, None, and bool
- Relational operators for equivalence and ordering
- Conditional code with if-elif-else
- While-loops
- While-loops expressions converted to bool
- Interrupt loops with Control-C
- Control-C generates a KeyboardInterrupt exception
- Break out of loops with break
- Exits the innter-most executing loop
- Takes execution to the first statement following the loop
- Augmented assignment operators like +=
- Request text input from the user with input()
Review, Python Update 2 for the changes to my notes here after the above lesson
Introducing Strings, Collections, & Iteration
Overview
- str, bytes, list, and dict
- for-loop
- Put it all together
Collections
- str
- Data type for strings in Python
- Sequence of Unicode code points
- Immutable
- String Literals - "" / ''
- Escape Sequences - \n \' \"
- String Features
- Unicode Strings
- bytes
- Data type for sequences of bytes
- Raw binary data
- Fixed-width single-byte encodings
- Convert Between Strings and Bytes
- list
- Sequences of objects
- Mutable
- Workhorse in Python
- dict
- Fundamental data structure in Python
- Map keys to values
- Also known as maps or associative arrays
- for-loops
- Visit each item for an iterable sequence
Put it all together
Summary
- Single- and multi-line literals
- Concatenation of adjacent literals
- Universal newlines
- Escape sequences
- Raw strings
- Use str constructor to convert other types
- Access individual characters with square bracket indexing
- Rich API
- String literals can contain Unicode
- Bytes
- Sequence of bytes rather than codepoints
- Literals prefixed with lowercase "b"
- Use str.encode() and bytes.decode() for conversion
- Lists
- Mutable, heterogeneous sequences
- Literals delimited by square brackets
- Literal items separated by commas
- Access elements with square brackets
- Elements can be replaced by assigning to an index
- Grow lists with append()
- Use list constructor to create lists from other sequences
- Dicts
- Associate keys with values
- Literals are delimited by curly braces
- Key-value pairs are separated by commas
- Keys are separated from values by colons
- For-loops
- Bind each item from an iterable one at a time to a name
- Called for-each loops in other languages
Modularity
Overview
- Reusable functions
- Source code files called modules
- Modules can be used from other modules
- Importing modules
- Programs or scripts
- Python execution model
- Make programs executable
Modularity
- Module code is only executed once on first import
Functions
- Functions are defined with the def keyname followed by the function name, and argument list in ()
- functions are called via the function name with arguments: my_function(my_argument)
- Many language features are implemented or controlled using specially named objects & functions. Such as, __feature__, known as a dunder.
- Dunder is a portmanteau of "double underscore"
__name__
- Specially named variable allowing to detect whether a module is run as a script or imported into another module
Python Execution Model
- def is a statement
- Top-level functions are defined when a module is imported or run
Docstrings
- Literal strings which document functions, modules, & classes
- They must be the first statement in the blocks for these constructs:"""Documentation strings"""
- Module docstrings must be at the start of the module before any statments
- PEP 257: Official Python convention for docstrings
- Sphinx: Tool to create HTML documentation from Python docstrings
- Google Style Guide
- help(function_name) can access the help from the REPL
Comments
- Code is ideally clear enough without ancillary explanation
- Sometimes you need to explain why your code is written as it is
- Comments in Python start with # & extend to the end of the line
Summary
- Python code is generally place in *.py files
- Execute modules by passing them as the first argument to Python
- All top-level statements are executed when a module is imported
- Define functions with the def keyword
- Return objects from functions with the return keyword
- return without an argument returns None, as does the implicit return
- Use __name__ to determine how a module is being used
- if __name__ == '__main__' lets the module be executable & importable
- A module is executed once, on first import
- def is a statement which binds code to a name
- sys.argv contains command line arguments
- Dynamic typing supports generic programming
- Functions can have docstrings
- help() can retrieve docstrings
- Modules can have docstrings
- Python comments start with #
- Program loaders can use #! (Shebang) to determine which Python to run
Objects & Types
Overview
- Python object model
- Named references to objects
- Value vs. identity equality
- Value-equality & identity equality are fundamentally different concepts
- Comparison by value can be controlled programatically
- Identity comparison is unalterably defined by the language
- Passing arguments & returning values
- Python's type system
- Scopts to limit name access
- "Everything is an object"
Passing Arguments & Returning Values
- Function arguments are transferred using pass-by-object-reference
- References to objects are copied, not the objects themselves
Function Arguments
- Arguments with default values must come after those without default values
- Default Value Evaluation
- def is a statement executed at runtime
- Default arguments are evaluated when def is executed
- Immutable default values don't cause problems
- Mutable default values can cause confusing effects
- Always use immutable objects for default values
Python's Type System
- Python will not generally perform implicit conversions between types
- The exception to this rule is the conversion of if statement & while loop predicates to bool
- Type declarations are unnecessary in Python
- Names can be rebound as necessary to objects of any type
Scopes
- Name resolution to objects is managed by scopes & scoping rules
- Four types of scope in Python arranged in the hierarchy (from narrowest to broadest
- Local: Inside the current function
- Enclosing: Inside enclosing functions
- Global: At the top level of the module
- Built-in: In the special builtins module
- Scopes in Python do not correspond to source code blocks as demarcated by indentation
- global: Rebind global names into a local namespace
"Everything is an Object"
- Determine the type of any object by using the type built in function
- Attributes of an object can be viewed with the dir built in function in a Python interactive session
Summary
- Python uses named references to objects
- Assignment attaches a name to an object
- Assigning one name to another makes them both point at the same object
- The garbage collector removes objects with no references
- id() returns a unique integer ID for an object
- is determines if two names refer to the same object
- We can test for equivalence with ==
- Function arguments are passed by object reference
- Rebinding function arguments loses the original object reference
- return passes back an object reference to the caller
- Function arguments may have a default value
- Default argument values are evaluated once, when the function is defined
- Python uses dynamic typing
- Python has strong typing
- Python names are looked up using the LEGB rule
- Global references can be read from local scopes
- Use global to assign to global references from a local scope
- Everything in Pyton is an object
- import & def bind names to objects
- type() reports the type of an object
- dir() introspects the attributes of an object
- You can access the name of a function or module with __name__
- Docstrings can be accessed though __doc__
- You can use len() to measure the length of a string
- The repetition operator, *, repeats a string an integral number of times
Built-in Collections
Overview
- Deeper look at str, list, & dict
- New collection types:
- tuple
- range
- set
- Protocols that unite collections
tuples
- immutable sequences of arbitrary objects
- Once created, the objects within them cannot be replaced or removed, and new elements cannot be added.
- Similar syntax to lists, except they are delimited by parentheses rather than square brackets
Tuple unpacking
- Destructuring operation that unpacks data structures into named references